package com.mp3player.mp3player;


import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;

import com.mp3player.model.Mp3Info;
import com.mp3player.util.FileUtils;
import com.mp3player.util.MetaData;
import com.mp3player.util.ToolUtils;

import java.util.List;


/**
 * A simple {@link Fragment} subclass.
 */
public class LocalMp3ListFragment extends Fragment {

    private View rootView = null;

    private ListView localMp3List = null;

    List<Mp3Info> mp3InfoList = null;

    public LocalMp3ListFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        rootView = inflater.inflate(R.layout.fragment_local_mp3_list, container, false);
        //获得ListView
        localMp3List = (ListView) rootView.findViewById(R.id.local_mp3_list);
        //刷新ListView
        refreshLocalMp3List();
        //为ListView绑定每一行的点击监听器
        localMp3List.setOnItemClickListener(new LocalMp3ListItemSelectListener());

        return rootView;
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        if (isVisibleToUser) {
            refreshLocalMp3List();
        }
        super.setUserVisibleHint(isVisibleToUser);
    }

    private void refreshLocalMp3List() {
        System.out.println("refresh local mp3 list...");
        //刷新mp3播放列表
        mp3InfoList = FileUtils.getMp3Files(MetaData.root.getAbsolutePath()+FileUtils.SEPERATOR+MetaData.SAVE_DIR);
        ToolUtils.renderMp3ListView(mp3InfoList, getContext(), localMp3List);
    }

    class LocalMp3ListItemSelectListener implements AdapterView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Mp3Info mp3Info = mp3InfoList.get(position);
            Intent intent = new Intent();
            intent.putExtra(MetaData.MP3_INFO_KEY, mp3Info);
            intent.setClass(rootView.getContext(), PlayerActivity.class);
            rootView.getContext().startActivity(intent);
        }
    }

}
